package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"role-perm/cache"
	"role-perm/models"
	"role-perm/pkg"
	"time"
)

func UserLogin(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "用户名和密码不能为空",
		})
		return
	}
	var user models.User
	login_key := "login_key" + username
	errcount, _ := cache.Rdb.Get(cache.Ctx, login_key).Int()
	if errcount > 3 {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "密码错误3次",
		})
		return
	}
	if user.Password != pkg.Md5Str(password) {
		if errcount == 2 {
			cachejson, _ := json.Marshal(user)
			cache.Rdb.Set(cache.Ctx, login_key, cachejson, time.Hour*2)
			c.JSON(http.StatusOK, gin.H{
				"code": 0,
				"msg":  "密码错误三次，封禁2小时",
			})
			return
		}
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "登录成功",
		})
	}
}
func List(c *gin.Context) {

}
